<template>
  <el-form
    ref="editFormRef"
    :model="editForm"
    :rules="rules"
    label-width="100px"
    class="edit-form"
  >
    <!-- 题型 -->
    <el-form-item label="题目类型" prop="questionType">
      <el-select :disabled="props.disabled" v-model="editForm.questionType" class="form-select">
        <el-option
          v-for="item in options.filter(item => item.value !== 'all')"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <!-- 题干 -->
    <el-form-item label="题目内容" prop="stem">
      <template v-if="editForm.questionType === 'READING'">
        <el-input
          v-model="editForm.passage"
          type="textarea"
          :rows="4"
          placeholder="请输入阅读文章内容"
        />
      </template>
      <template v-else>
        <el-input
          v-model="editForm.stem"
          type="textarea"
          :rows="3"
          placeholder="请输入题目内容"
        />
      </template>
    </el-form-item>

    <!-- 选项（单选和多选题） -->
    <template v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(editForm.questionType)">
      <el-form-item
        v-for="(option, index) in editForm.options"
        :key="index"
        :label="'选项' + option.optionId"
        :prop="'options.' + index + '.content'"
        :rules="{ required: true, message: '选项内容不能为空', trigger: 'blur' }"
      >
        <div class="option-edit">
          <el-input v-model="option.content" placeholder="请输入选项内容" />
          <el-button
            type="danger"
            circle
            @click="removeOption(index)"
            :disabled="editForm.options.length <= 2"
            class="remove-btn"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          plain
          @click="addOption"
          :disabled="editForm.options.length >= 6"
        >
          添加选项
        </el-button>
      </el-form-item>
    </template>

    <!-- 答案 -->
    <el-form-item label="答案" prop="answer">
      <template v-if="editForm.questionType === 'SINGLE_CHOICE'">
        <el-select v-model="editForm.answer" class="form-select">
          <el-option
            v-for="option in editForm.options"
            :key="option.optionId"
            :label="option.optionId"
            :value="option.optionId"
          />
        </el-select>
      </template>
      <template v-else-if="editForm.questionType === 'MULTIPLE_CHOICE'">
        <el-select
          v-model="editForm.answers_tmp"
          multiple
          class="form-select"
          @change="handleMultipleAnswerChange"
        >
          <el-option
            v-for="option in editForm.options"
            :key="option.optionId"
            :label="option.optionId"
            :value="option.optionId"
          />
        </el-select>
      </template>
      <template v-else-if="editForm.questionType === 'TRUE_FALSE'">
        <el-radio-group v-model="editForm.answer">
          <el-radio label="TRUE">正确</el-radio>
          <el-radio label="FALSE">错误</el-radio>
        </el-radio-group>
      </template>
      <template v-else>
        <el-input
          v-model="editForm.answers[0]"
          type="textarea"
          :rows="2"
          placeholder="请输入答案"
        />
      </template>
    </el-form-item>

    <!-- 难度 -->
    <el-form-item label="难度" prop="difficulty">
      <el-select v-model="editForm.difficulty" class="form-select">
        <el-option label="简单" :value="1" />
        <el-option label="中等" :value="2" />
        <el-option label="困难" :value="3" />
      </el-select>
    </el-form-item>

    <!-- 解析 -->
    <el-form-item label="答案解析" prop="analysis">
      <el-input
        v-model="editForm.analysis"
        type="textarea"
        :rows="3"
        placeholder="请输入答案解析"
      />
    </el-form-item>

    <!-- 知识点 -->
    <el-form-item label="知识点" prop="knowledgePoints">
      <el-select
        v-model="editForm.knowledgePoints"
        multiple
        filterable
        allow-create
        default-first-option
        class="form-select"
        placeholder="请输入或选择知识点"
      >
        <el-option
          v-for="point in knowledgePointOptions"
          :key="point"
          :label="point"
          :value="point"
        />
      </el-select>
    </el-form-item>

    <!-- 填空题答案 -->
    <template v-if="editForm.questionType === 'FILL_BLANK'">
      <el-form-item
        v-for="(_, index) in (editForm.blanks ? editForm.blanks.split('|') : [''])"
        :key="index"
        :label="'第' + (index + 1) + '空'"
        :prop="'blanks'"
      >
        <div class="blank-edit">
          <el-input 
            :model-value="editForm.blanks ? editForm.blanks.split('|')[index] : ''"
            placeholder="请输入答案"
            @update:model-value="(val) => handleBlankInput(val, index)" 
          />
          <el-button
            type="danger"
            circle
            @click="removeBlank(index)"
            :disabled="!editForm.blanks || editForm.blanks.split('|').length <= 1"
            class="remove-btn"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="addBlank">
          添加填空
        </el-button>
      </el-form-item>
    </template>

    <!-- 综合题子题目 -->
    <template v-if="editForm.questionType === 'READING'">
      <el-form-item label="子题目">
        <div class="sub-questions-container">
          <div v-for="(subQ, index) in editForm.subQuestions" :key="index" class="sub-question-edit">
            <div class="sub-question-header">
              <span class="sub-question-index">第{{ index + 1 }}小题</span>
              <el-button
                type="danger"
                circle
                @click="removeSubQuestion(index)"
                :disabled="editForm.subQuestions.length <= 1"
                class="remove-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            
            <!-- 题型选择 -->
            <el-form-item label="题目类型" :prop="'subQuestions.' + index + '.questionType'">
              <el-select v-model="subQ.questionType" class="form-select">
                <el-option
                  v-for="type in subQuestionTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
            
            <!-- 题目内容 -->
            <el-form-item label="题目内容" :prop="'subQuestions.' + index + '.stem'">
              <el-input
                v-model="subQ.stem"
                type="textarea"
                :rows="2"
                placeholder="请输入子题目内容"
              />
            </el-form-item>
            
            <!-- 选择题选项 -->
            <template v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(subQ.questionType)">
              <el-form-item
                v-for="(option, optIndex) in subQ.options"
                :key="optIndex"
                :label="'选项' + option.optionId"
                :prop="'subQuestions.' + index + '.options.' + optIndex + '.content'"
              >
                <div class="option-edit">
                  <el-input v-model="option.content" placeholder="请输入选项内容" />
                  <el-button
                    type="danger"
                    circle
                    @click="removeSubOption(index, optIndex)"
                    :disabled="subQ.options.length <= 2"
                    class="remove-btn"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  plain
                  @click="addSubOption(index)"
                  :disabled="subQ.options.length >= 6"
                >
                  添加选项
                </el-button>
              </el-form-item>
            </template>

            <!-- 填空题答案 -->
            <template v-if="subQ.questionType === 'FILL_BLANK'">
              <el-form-item label="填空答案" :prop="'subQuestions.' + index + '.blanks'">
                <div v-for="(blank, blankIndex) in (subQ.blanks ? subQ.blanks.split('|') : [])" 
                     :key="blankIndex" 
                     class="blank-input">
                  <el-input
                    :model-value="blank"
                    placeholder="请输入填空答案"
                    @update:model-value="(val) => handleSubBlankInput(val, index, blankIndex)"
                  />
                  <el-button
                    type="danger"
                    circle
                    @click="removeSubBlank(index, blankIndex)"
                    :disabled="!subQ.blanks || subQ.blanks.split('|').length <= 1"
                    class="remove-btn"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
                <el-button type="primary" plain @click="addSubBlank(index)">
                  添加填空
                </el-button>
              </el-form-item>
            </template>

            <!-- 判断题答案 -->
            <template v-if="subQ.questionType === 'TRUE_FALSE'">
              <el-form-item label="答案" :prop="'subQuestions.' + index + '.answer'">
                <el-radio-group v-model="subQ.answer">
                  <el-radio label="TRUE">正确</el-radio>
                  <el-radio label="FALSE">错误</el-radio>
                </el-radio-group>
              </el-form-item>
            </template>

            <!-- 选择题答案 -->
            <template v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(subQ.questionType)">
              <el-form-item label="答案" :prop="'subQuestions.' + index + '.answer'">
                <template v-if="subQ.questionType === 'SINGLE_CHOICE'">
                  <el-select v-model="subQ.answer" class="form-select">
                    <el-option
                      v-for="option in subQ.options"
                      :key="option.optionId"
                      :label="option.optionId"
                      :value="option.optionId"
                    />
                  </el-select>
                </template>
                <template v-else>
                  <el-select
                    v-model="subQ.answers"
                    multiple
                    class="form-select"
                    @change="(val) => handleSubMultipleAnswerChange(val, index)"
                  >
                    <el-option
                      v-for="option in subQ.options"
                      :key="option.optionId"
                      :label="option.optionId"
                      :value="option.optionId"
                    />
                  </el-select>
                </template>
              </el-form-item>
            </template>

            <!-- 简答题答案 -->
            <template v-if="['SHORT_ANSWER', 'FILL_BLANK'].includes(subQ.questionType)">
              <el-form-item label="答案" :prop="'subQuestions.' + index + '.answer'">
                <el-input
                  v-model="subQ.answer"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入答案"
                />
              </el-form-item>
            </template>
            
            <!-- 解析 -->
            <el-form-item label="解析" :prop="'subQuestions.' + index + '.analysis'">
              <el-input
                v-model="subQ.analysis"
                type="textarea"
                :rows="2"
                placeholder="请输入解析"
              />
            </el-form-item>
            
            <!-- 分值 -->
            <el-form-item label="分值" :prop="'subQuestions.' + index + '.score'">
              <el-input-number
                v-model="subQ.score"
                :min="1"
                :max="100"
                controls-position="right"
              />
            </el-form-item>
          </div>
          
          <div class="add-sub-question-btn">
            <el-button type="primary" plain @click="addSubQuestion">
              添加子题目
            </el-button>
          </div>
        </div>
      </el-form-item>
    </template>

    <!-- 底部按钮 -->
    <div class="form-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
    </div>
  </el-form>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'


const props = defineProps({
  question: {
    type: Object,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['save', 'cancel'])

// 表单引用
const editFormRef = ref(null)
const saving = ref(false)
// 编辑表单数据
const editForm = ref({
  questionType: 'SINGLE_CHOICE',
  stem: '',
  options: [
    { optionId: 'A', content: '' },
    { optionId: 'B', content: '' }
  ],
  answers: [''],
  answer: '',
  difficulty: 1,
  analysis: '',
  knowledgePoints: [],
  passage: '',
  blanks: '',
  subQuestions: []
});

// 初始化表单数据
const initFormData = (questionData) => {
  // 创建基础默认表单结构
  const defaultForm = {
    questionType: 'SINGLE_CHOICE',
    stem: '',
    options: [
      { optionId: 'A', content: '' },
      { optionId: 'B', content: '' }
    ],
    answers: [''],
    answer: '',
    difficulty: 1,
    analysis: '',
    knowledgePoints: [],
    passage: '',
    blanks: '',
    subQuestions: []
  };
  
  // 合并传入的问题数据与默认值
  const formData = { ...defaultForm, ...questionData };
  
  // 为多选题设置临时答案数组
  if (formData.questionType === "MULTIPLE_CHOICE" && formData.answers && formData.answers[0]) {
    formData.answers_tmp = formData.answers[0].split(',');
  } else if (formData.questionType === "MULTIPLE_CHOICE") {
    formData.answers_tmp = [];
  }
  
  // 确保选择题有选项
  if ((formData.questionType === 'SINGLE_CHOICE' || formData.questionType === 'MULTIPLE_CHOICE') 
      && (!formData.options || formData.options.length === 0)) {
    formData.options = [
      { optionId: 'A', content: '' },
      { optionId: 'B', content: '' }
    ];
  }
  
  // 确保综合题题有子题目
  if (formData.questionType === 'READING' && (!formData.subQuestions || formData.subQuestions.length === 0)) {
    formData.subQuestions = [{
      questionType: 'SINGLE_CHOICE',
      stem: '',
      options: [
        { optionId: 'A', content: '' },
        { optionId: 'B', content: '' }
      ],
      answer: '',
      analysis: '',
      score: 5
    }];
  }
  
  editForm.value = formData;
};

// 初始化
onMounted(() => {
  console.log(props.question);
  initFormData(props.question);
});

// 监听题目数据变化
watch(
  () => props.question,
  (newQuestion) => {
    initFormData(newQuestion);
  }
);

// 题型选项
const options = [
  { value: 'all', label: '全部' },
  { value: 'SINGLE_CHOICE', label: '单选题' },
  { value: 'MULTIPLE_CHOICE', label: '多选题' },
  { value: 'TRUE_FALSE', label: '判断题' },
  { value: 'FILL_BLANK', label: '填空题' },
  { value: 'SHORT_ANSWER', label: '简答题' },
  { value: 'READING', label: '综合题' }
]

// 子题目可选题型（排除综合题）
const subQuestionTypes = computed(() => 
  options.filter(item => item.value !== 'all' && item.value !== 'READING')
)

// 知识点选项（可以从后端获取或本地维护）
const knowledgePointOptions = ref([
  '第一章:关键字',
  '第一章:类和对象',
  '第二章:数据类型',
  '第二章:数组',
  '第三章:基本数据类型',
  '第三章:引用数据类型',
  '面向对象:多态性'
])

// 表单验证规则
const rules = {
  questionType: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  stem: [
    { 
      required: true, 
      validator: (rule, value, callback) => {
        // 如果是综合题题，stem不是必填
        if (editForm.value.questionType === 'READING') {
          callback()
        } else if (!value) {
          callback(new Error('请输入题目内容'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  passage: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (editForm.value.questionType === 'READING' && !value) {
          callback(new Error('请输入阅读文章内容'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  answer: [
    {
      required: true,
      validator: (rule, value, callback) => {
        // 填空题和综合题题不需要验证answer字段
        if (['FILL_BLANK', 'READING'].includes(editForm.value.questionType)) {
          callback()
        } else if (!value && !editForm.value.answers?.[0]) {
          callback(new Error('请选择或输入答案'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  blanks: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (editForm.value.questionType === 'FILL_BLANK') {
          if (!editForm.value.blanks) {
            callback(new Error('请至少添加一个填空答案'))
          } else {
            const blanks = editForm.value.blanks.split('|')
            if (blanks.some(blank => !blank.trim())) {
              callback(new Error('填空答案不能为空'))
            } else {
              callback()
            }
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  subQuestions: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (editForm.value.questionType === 'READING') {
          if (!editForm.value.subQuestions || editForm.value.subQuestions.length === 0) {
            callback(new Error('请至少添加一个子题目'))
          } else {
            // 验证每个子题目
            const invalidSubQuestion = editForm.value.subQuestions.find(subQ => {
              return !subQ.stem || !subQ.answer || !subQ.score ||
                (subQ.options && subQ.options.length > 0 && subQ.options.some(opt => !opt.content))
            })
            
            if (invalidSubQuestion) {
              callback(new Error('请完善子题目的所有必填信息'))
            } else {
              callback()
            }
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ]
}

// 监听题型变化
watch(() => editForm.value.questionType, (newType) => {
  // 重置相关字段
  if (newType === 'SINGLE_CHOICE' || newType === 'MULTIPLE_CHOICE') {
    if (!editForm.value.options || editForm.value.options.length === 0) {
      editForm.value.options = [
        { optionId: 'A', content: '' },
        { optionId: 'B', content: '' }
      ]
    }
  } else if (newType === 'READING') {
    if (!editForm.value.subQuestions || editForm.value.subQuestions.length === 0) {
      editForm.value.subQuestions = [{
        questionType: 'SINGLE_CHOICE',
        stem: '',
        options: [
          { optionId: 'A', content: '' },
          { optionId: 'B', content: '' }
        ],
        answer: '',
        analysis: '',
        score: 5
      }]
    }
  }
})

// 添加选项
const addOption = () => {
  const newOptionId = String.fromCharCode(65 + editForm.value.options.length)
  editForm.value.options.push({
    optionId: newOptionId,
    content: ''
  })
}

// 删除选项
const removeOption = (index) => {
  editForm.value.options.splice(index, 1)
  // 重新排序选项ID
  editForm.value.options.forEach((option, idx) => {
    option.optionId = String.fromCharCode(65 + idx)
  })
}

// 处理多选题答案变化
const handleMultipleAnswerChange = (value) => {
  if (!value) return;
  
  editForm.value.answers_tmp = value;
  if (!editForm.value.answers) {
    editForm.value.answers = [''];
  }
  editForm.value.answers[0] = value.join(',');
}

// 添加填空
const addBlank = () => {
  if (!editForm.value.blanks) {
    editForm.value.blanks = ''
  }
  editForm.value.blanks = editForm.value.blanks ? editForm.value.blanks + '|' : ''
}

// 删除填空
const removeBlank = (index) => {
  const blanks = editForm.value.blanks.split('|')
  blanks.splice(index, 1)
  editForm.value.blanks = blanks.join('|')
}

// 处理填空输入
const handleBlankInput = (value, index) => {
  const blanks = editForm.value.blanks ? editForm.value.blanks.split('|') : []
  blanks[index] = value
  editForm.value.blanks = blanks.join('|')
}

// 添加子题目
const addSubQuestion = () => {
  if (!editForm.value.subQuestions) {
    editForm.value.subQuestions = []
  }
  editForm.value.subQuestions.push({
    questionType: 'SINGLE_CHOICE',
    stem: '',
    options: [
      { optionId: 'A', content: '' },
      { optionId: 'B', content: '' }
    ],
    answer: '',
    analysis: '',
    score: 5
  })
}

// 删除子题目
const removeSubQuestion = (index) => {
  editForm.value.subQuestions.splice(index, 1)
}

// 添加子题目选项
const addSubOption = (subQuestionIndex) => {
  const subQ = editForm.value.subQuestions[subQuestionIndex]
  const newOptionId = String.fromCharCode(65 + subQ.options.length)
  subQ.options.push({
    optionId: newOptionId,
    content: ''
  })
}

// 删除子题目选项
const removeSubOption = (subQuestionIndex, optionIndex) => {
  const subQ = editForm.value.subQuestions[subQuestionIndex]
  subQ.options.splice(optionIndex, 1)
  // 重新排序选项ID
  subQ.options.forEach((option, idx) => {
    option.optionId = String.fromCharCode(65 + idx)
  })
}

// 添加子题目填空
const addSubBlank = (index) => {
  if (!editForm.value.subQuestions[index].blanks) {
    editForm.value.subQuestions[index].blanks = ''
  }
  editForm.value.subQuestions[index].blanks = editForm.value.subQuestions[index].blanks ? editForm.value.subQuestions[index].blanks + '|' : ''
}

// 删除子题目填空
const removeSubBlank = (index, blankIndex) => {
  const blanks = editForm.value.subQuestions[index].blanks.split('|')
  blanks.splice(blankIndex, 1)
  editForm.value.subQuestions[index].blanks = blanks.join('|')
}

// 处理子题目填空输入
const handleSubBlankInput = (value, index, blankIndex) => {
  const blanks = editForm.value.subQuestions[index].blanks ? editForm.value.subQuestions[index].blanks.split('|') : []
  blanks[blankIndex] = value
  editForm.value.subQuestions[index].blanks = blanks.join('|')
}

// 处理子题目多选答案变化
const handleSubMultipleAnswerChange = (value, index) => {
  const subQ = editForm.value.subQuestions[index]
  subQ.answers = value
  subQ.answer = value.join(',')
}

// 保存题目
const handleSave = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      emit('save', editForm.value)
    }
  })
}

// 取消编辑
const handleCancel = () => {
  emit('cancel')
}

</script>

<style scoped>
.edit-form {
  padding: 20px;
}

.form-select {
  width: 100%;
}

.option-edit,
.blank-edit {
  display: flex;
  gap: 10px;
  align-items: center;
}

.remove-btn {
  flex-shrink: 0;
}

.sub-questions-container {
  width: 100%;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.sub-question-edit {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.sub-question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.sub-question-index {
  font-weight: bold;
  color: #409EFF;
}

.add-sub-question-btn {
  margin-top: 15px;
  text-align: center;
}

.form-footer {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style> 